package learnjava.basic.other;

import java.net.DatagramPacket;
import java.net.DatagramSocket;
import java.net.InetAddress;

public class TestUDP {

    public static void main(String[] args) throws Exception{
        //1，正常接收
//        new Receiver().start();
//        new Sender().start();
        //sender:已发出
        //receiver:已接收
        //UDP方式消息

        //2，接收不到
        new Sender().start();
        Thread.sleep(1000);
        new Receiver().start();
        //sender:已发出
        //之后Receiver一直在等

    }

}

class Sender extends Thread{

    @Override
    public void run() {
        try {
            DatagramSocket datagramSocket = new DatagramSocket();
            byte[] msg = "UDP方式消息".getBytes();
            InetAddress add = InetAddress.getLocalHost();
            DatagramPacket datagramPacket = new DatagramPacket(msg,0,msg.length,add,2021);
            datagramSocket.send(datagramPacket);
            System.out.println("sender:已发出");
            datagramSocket.close();
        }catch (Exception e){
            e.printStackTrace();
        }
    }
}

class Receiver extends Thread{
    @Override
    public void run() {
        try {
            DatagramSocket datagramSocket = new DatagramSocket(2021);
            byte[] buffer = new byte[128];
            DatagramPacket datagramPacket = new DatagramPacket(buffer,0,buffer.length);

            datagramSocket.receive(datagramPacket);
            System.out.println("receiver:已接收");
            System.out.println(new String(datagramPacket.getData(),0,datagramPacket.getLength()));
            datagramSocket.close();
        }catch (Exception e){
            e.printStackTrace();
        }

    }
}
